package com.ysactive.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.ysactive.config.BaseResponse;
import com.ysactive.config.FileConfiguration;
import com.ysactive.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * Notice:
 * 文件处理
 *
 * @author xuxu
 * @version 1.0
 * @date 2023/9/2
 * @since 1.0
 */
@RequiredArgsConstructor
@Controller
@RequestMapping("/file")
public class FileController {

    private final FileService fileService;

    private final HttpServletRequest request;

    private final FileConfiguration fileConfiguration;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/upload/image")
    public @ResponseBody BaseResponse<String> uploadImage(@RequestPart("file") MultipartFile file) {
        String extName = FileUtil.extName(file.getOriginalFilename());

        if (extName == null || !fileConfiguration.getImgExtName().contains(extName.toLowerCase())) {
            return BaseResponse.fail("上传失败，不是一个图片");
        }

        String path = fileService.uploadFile("image", file);
        return BaseResponse.success(path);
    }

    /**
     * 上传视频
     * @param file
     * @return
     */
    @PostMapping("/upload/video")
    public @ResponseBody BaseResponse<String> uploadVideo(@RequestPart("file") MultipartFile file) {

        String extName = FileUtil.extName(file.getOriginalFilename());

        if (extName == null || !fileConfiguration.getVideoExtName().contains(extName.toLowerCase())) {
            return BaseResponse.fail("上传失败，视频后缀名不正确，请选择正确的视频");
        }

        String path = fileService.uploadFile("video", file);
        return BaseResponse.success(path);
    }

    @PostMapping("/testEmail")
    public @ResponseBody BaseResponse<String> testEmail(String email, String title, String content){
        try {
            fileService.sendHtmlEmail(email, title, content, null);
        } catch (Exception e){
            e.printStackTrace();
        }
        return BaseResponse.success("发送成功");
    }

    /**
     * 下载或者在线播放（预览的话需要改下 media type）
     * @return
     */
    @GetMapping("/download/**")
    public ResponseEntity<byte[]> preview() {
        String uri = request.getRequestURI();
        String path = CharSequenceUtil.removePrefix(uri, "/file/preview");

        ApplicationHome h = new ApplicationHome(getClass());
        File source = h.getSource();

        byte[] bytes = FileUtil.readBytes(new File(source, "/file" + path));

        String originalFileName = path;//由于没有存数据库，拿不到原始文件名

        String fileName = new String(originalFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }


}
